﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class administrator_AnhQuangCao : System.Web.UI.Page
{
    dulieuDataContext db=new dulieuDataContext();
    protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack)
        {
            LoadAnhToDropDown();
            LoadAnh(Convert.ToInt32(drdvitridanganh.SelectedValue));
        }
    }
    protected void LoadAnhToDropDown()
    {
        drdvitridanganh.DataSource = from o in db.TypesImages select o;
        drdvitridanganh.DataTextField = "Name";
        drdvitridanganh.DataValueField = "ID";
        drdvitridanganh.DataBind();
    }
    protected void imbtthem_Click(object sender, ImageClickEventArgs e)
    {
        var Anh = new Img()
                      {Image = GetFilePic(), Link = txtlink.Text, ID = Convert.ToInt32(drdvitridanganh.SelectedValue)};
        db.Imgs.InsertOnSubmit(Anh);
        db.SubmitChanges();
        LoadAnh(Convert.ToInt32(drdvitridanganh.SelectedValue));
        
    }
    protected void LoadAnh(int id)
    {
        rpt_anh.DataSource = from o in db.Imgs where o.ID == id select o;
        rpt_anh.DataBind();
    }
    public string GetFilePic()
    {
        var sfile = "";
        if (FileUpLoad1.HasFile)
        {
            sfile = Guid.NewGuid().ToString().Substring(0, 10) + FileUpLoad1.PostedFile.FileName.Remove(0, FileUpLoad1.PostedFile.FileName.LastIndexOf("."));
            FileUpLoad1.PostedFile.SaveAs(Server.MapPath("~/images/") + sfile);
        }
        return sfile;
    }
    protected void drdvitridanganh_SelectedIndexChanged(object sender, EventArgs e)
    {
        LoadAnh(Convert.ToInt32(drdvitridanganh.SelectedValue));
        
    }
    protected void ImageButton2_Click(object sender, ImageClickEventArgs e)
    {
        foreach (RepeaterItem item in rpt_anh.Items)
        {
            var chk = (CheckBox) item.FindControl("chk");
            if (chk.Checked)
            {
                var lblid = (Label) item.FindControl("lblid");
                var anh = (from o in db.Imgs where o.IdImage == Convert.ToDecimal(lblid.Text) select o).SingleOrDefault();
                db.Imgs.DeleteOnSubmit(anh);
                db.SubmitChanges();
            }
        }
        lblthongbao.Text = "Xóa thành công";
        LoadAnh(Convert.ToInt32(drdvitridanganh.SelectedValue));
    }
}
